import React, { Component } from 'react';
import PubSub from 'pubsub-js';
import './index.css'

export default class List extends Component {
    state = {
        items: [],
        isFirst: true,//保存用户是否第一次请求
        isLoading:false,//保存是否在加载中
        errMsg: '',
    }
    render() {
        const { items, isFirst, isLoading, errMsg } = this.state;
        return (
            <div className="row">
                {
                    isFirst ? <h2>欢迎使用github搜索功能</h2> :
                        isLoading ? <h2>正在加载，请等待</h2> :
                            errMsg ? <h1>{errMsg.message}</h1> :
                                items.map(item => {
                                    const { id, avatar_url, html_url, login } = item;
                                    return (
                                        <div key={id} className="card">
                                            <a href={html_url} target="_blank" rel="noreferrer">
                                                <img src={avatar_url} style={{ width: '100px' }} alt='avatar' />
                                            </a>
                                            <p className="card-text">{login}</p>
                                        </div>
                                    )
                                })
                }

            </div>
        )
    }

    componentDidMount() {
         //subscribe回调函数接收两个参数，第一个是当前订阅的名字,第二个参数是发布的信息
        PubSub.subscribe('updateList', (_, data) => {
            console.log('这是List订阅', data);//updateList  search发布的
            this.setState(data);
        })
    }
}

/*  res.data.items
avatar_url: "https://avatars.githubusercontent.com/u/1825798?v=4"
events_url: "https://api.github.com/users/1/events{/privacy}"
followers_url: "https://api.github.com/users/1/followers"
following_url: "https://api.github.com/users/1/following{/other_user}"
gists_url: "https://api.github.com/users/1/gists{/gist_id}"
gravatar_id: ""
html_url: "https://github.com/1"
id: 1825798
login: "1"
node_id: "MDQ6VXNlcjE4MjU3OTg="
organizations_url: "https://api.github.com/users/1/orgs"
received_events_url: "https://api.github.com/users/1/received_events"
repos_url: "https://api.github.com/users/1/repos"
score: 1
site_admin: false
starred_url: "https://api.github.com/users/1/starred{/owner}{/repo}"
subscriptions_url: "https://api.github.com/users/1/subscriptions"
type: "User"
url: "https://api.github.com/users/1"
*/